package com.amc.framework.filter;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * request.getInputStream()在@Responsebody使用之后会自动关闭，导致日志打印时出现request stream close问题，
 * 重写request构造方法，进行request缓存
 *
 * @author ZhangXX
 * @date @2021/10/15 17:09
 */

public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper {
    private byte[] body;

    public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws Exception {
        super(request);
        body = readBytes(request.getInputStream());

    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

    public static byte[] readBytes(InputStream is) throws Exception {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.flush();
        return bos.toByteArray();
    }

}
